package com.thunder.soft.vm;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.databinding.ObservableField;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.thunder.soft.R;
import com.thunder.soft.common.base.BaseBean;
import com.thunder.soft.common.base.BaseViewModel;
import com.thunder.soft.common.cache.CacheDataManager;
import com.thunder.soft.common.net.HttpClient;
import com.thunder.soft.ui.activity.AboutAutherActivity;
import com.thunder.soft.ui.activity.MyCollectActivity;
import com.thunder.soft.ui.activity.NotifyTestActivity;
import com.thunder.soft.ui.activity.OpenSourceActivity;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PersonViewModel extends BaseViewModel {

    private static String TAG=PersonViewModel.class.getName();
    public MutableLiveData<BaseBean<Object>> liveData = new MutableLiveData<>();
    public MutableLiveData<View> languageLiveData = new MutableLiveData<>();
    public MutableLiveData<View> imageLiveData = new MutableLiveData<>();
    public MutableLiveData<View> musicLiveData = new MutableLiveData<>();
    private Context mContext;
    public ObservableField<String> cacheText = new ObservableField<>();

    @Override
    public void onCreate(@NonNull LifecycleOwner owner) {
        super.onCreate(owner);
        try {
            cacheText.set(CacheDataManager.getTotalCacheSize(mContext));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void register(Context mContext) {
        this.mContext = mContext;
    }

    public void onItemClick(int index) {
        HashMap<String, Object> value = new HashMap<>();
        switch (index) {
            case 0:
                value.put("activity", MyCollectActivity.class);
                break;
            case 1:
                value.put("activity", OpenSourceActivity.class);
                break;
            case 2:
                value.put("activity", AboutAutherActivity.class);
                break;
            case 3:
                value.put("activity", NotifyTestActivity.class);
                break;
        }
        getActivityLiveData().postValue(value);
    }

    public void ControlMusicPlay(View view){
        musicLiveData.postValue(view);
    }

    public void Layout() {
        HttpClient.getInstance().request("user/logout/json", "GET", null, new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                getErrorMsg().postValue(e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Gson gson = new Gson();

                BaseBean<Object> BaseBean = gson.fromJson(response.body().string(),
                        new TypeToken<BaseBean<Object>>() {
                        }.getType());

                if (BaseBean.getErrorCode() == 0) {
                    liveData.postValue(BaseBean);
                } else {
                    getErrorMsg().postValue(BaseBean.getErrorMsg());
                }
            }
        });
    }

    public void onImageClick(View view) {
        imageLiveData.postValue(view);
    }

    public void onLanguageClick(View view) {
        languageLiveData.postValue(view);
    }

    public void onCacheClick() {
        new AlertDialog.Builder(mContext)
                .setTitle(mContext.getString(R.string.mine_tip))
                .setMessage("确定要清除缓存?")
                .setNegativeButton(mContext.getString(R.string.cancel), null)
                .setPositiveButton(mContext.getString(R.string.sure), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        new Thread(new clearCache()).start();
                    }
                })
                .show();
    }

    /**
     * 创建Handler
     * 接收消息
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(mContext, "清理完成", Toast.LENGTH_SHORT).show();
                    try {
                        cacheText.set(CacheDataManager.getTotalCacheSize(mContext));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
            }
        }
    };

    /**
     * 创建内部类，清除缓存
     */
    class clearCache implements Runnable {
        @Override
        public void run() {
            try {
                CacheDataManager.clearAllCache(mContext);
                Thread.sleep(1000);
                if (CacheDataManager.getTotalCacheSize(mContext).startsWith("0")) {
                    handler.sendEmptyMessage(0);
                }
            } catch (Exception e) {
                return;
            }
        }
    }

    public MutableLiveData<View> getLanguageLiveData() {
        return languageLiveData;
    }

    public MutableLiveData<View> getImageLiveData() {
        return imageLiveData;
    }

    public MutableLiveData<View> getMusicLiveData() {
        return musicLiveData;
    }

    public MutableLiveData<BaseBean<Object>> getLiveData() {
        return liveData;
    }
}